package com.learn.xueer.ui.viewmodel

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ToastUtils
import com.learn.xueer.app.appViewModel
import com.learn.xueer.app.network.ApiService
import com.learn.xueer.app.network.ApiService.Companion.SERVER_URL
import com.learn.xueer.app.network.MyHeadInterceptor
import com.learn.xueer.app.network.NetworkApi
import com.learn.xueer.app.network.apiService
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.data.model.bean.AreaResponse
import com.learn.xueer.data.model.bean.Child
import com.learn.xueer.data.model.bean.SchoolResponse
import com.learn.xueer.data.model.bean.UserInfoResponse
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.network.interceptor.logging.LogInterceptor
import me.hgj.jetpackmvvm.state.ResultState
import me.hgj.jetpackmvvm.util.LogUtils
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import java.util.Random


class RequestLoginViewModel : BaseViewModel() {
    /**
     * 17634547883
     * 112233
     */
    var username = StringObservableField()
    var realUsername = StringObservableField()
    var capture = MutableLiveData<String>().apply { postValue("") }
    var captureMobile = MutableLiveData<String>().apply { postValue("") }
    var random = ""
    var loginType = 0

    var password = StringObservableField()
    var realPassword = StringObservableField()
    var schoolResult = MutableLiveData<ResultState<ArrayList<SchoolResponse>?>>()
    var captchaData = MutableLiveData<ByteArray>()
    var selectSchool = MutableLiveData<Child>()
    fun aboutReq() {
        request({ apiService.getAbout() }, {
            //请求成功 已自动处理了 请求结果是否正常
            appViewModel.about.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
        }, true)

    }

    fun areaReq(back: (AreaResponse?) -> Unit) {
        request({ apiService.area() }, {
            //请求成功 已自动处理了 请求结果是否正常
            back(it)
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
        }, true)

    }

    fun loginReq(name: String, pass: String, id: String) {
        request({
            apiService.login(
                capture.value ?: "",
                random,
                name,
                pass,
                id, "2"
            )
        }, {
            ToastUtils.showShort("登录成功")
            if (loginType == 0) {
                CacheUtil.insertLoginAccount(name, pass)
            }
            CacheUtil.setToken(it?.userinfo?.token ?: "")
            userInfoReq()
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
            captcha()
        }, true, "正在登录中...")
    }

    fun resetPassReq(success: () -> Unit) {
        request({
            apiService.resetPass(
                capture.value ?: "",
                random,
                username.get(),
                captureMobile.value ?: "",
                password.get()
            )
        }, {
            ToastUtils.showShort("重置密码成功")
            success()
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }

    fun sendSmsReq(type: String) {
        request({
            apiService.sendSms(
                username.get(),
                type
            )
        }, {
            ToastUtils.showShort("发送验证码成功")
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }


    fun changeMobileReq(success: () -> Unit) {
        request({
            apiService.changeMobile(
                capture.value ?: "",
                random,
                username.get(),
                captureMobile.value ?: ""
            )
        }, {
            ToastUtils.showShort("验证手机号成功")
            success()
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }

    fun schoolListReq(city: String, name: String) {
        request(
            {
                apiService.getSchoolList(
                    city, name
                )
            }, schoolResult
        )
    }

    //         fun captcha() {
//        random = Random().nextInt(10000000).toString()
//        LogUtils.debugInfo("random:$random")
//        requestNoCheck({ HttpRequestCoroutine.captcha(random) }, {
//            if (it != null) {
//                captchaData.value = it
//            }
//        }, {
//            ToastUtils.showShort(it.errorMsg)
//        }, true)
//
//    }
    fun captcha() {

        var with = RetrofitUrlManager.getInstance().with(OkHttpClient.Builder())
            .addInterceptor(LogInterceptor())
            .cookieJar(NetworkApi.INSTANCE.cookieJar)
            .addInterceptor(MyHeadInterceptor())
            .build()
        random = Random().nextInt(10000000).toString()
        LogUtils.debugInfo("random:$random")
        val retrofit = Retrofit.Builder()
            .baseUrl(SERVER_URL)
            .client(with)
            .build()
        val service: ApiService = retrofit.create(ApiService::class.java)
        val call: Call<ResponseBody> = service.captcha(random)
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.isSuccessful) {
                    val body: ResponseBody? = response.body()
                    if (body != null) {
                        captchaData.value = body.bytes()

                    }
                } else {

                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
            }

        })

    }

    var userInfo = MutableLiveData<ResultState<UserInfoResponse?>>()

    fun userInfoReq() {
        request(
            {
                apiService.getUserInfo()
            }, userInfo, true
        )
    }

}